//
//  KPermissionViewController.m
//  Keping
//
//  Created by 柯平 on 2017/10/10.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KPermissionViewController.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "KPermissionCell.h"
#import "KUserData.h"
#import <CoreLocation/CoreLocation.h>
#import <Contacts/Contacts.h>
#import "GPContactRequest.h"

@interface KPermissionViewController ()
@property(nonatomic,strong)NSArray* items;
@property (nonatomic, strong) HJVisitFriendInfoModel *visitFriendInfoModel;

@end

@implementation KPermissionViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"App Permissions";
    [self getData];
    self.items = @[
  @{@"title":@"Allow Contact List Access",
                     @"content":@"In order to help you to fine your friends that already  using LinkTim,as well as invting friendsto your house,we need permssion to access your contact list and synchronize with our server securely.\nwe will never store your contact list or share it with anyone."},
  @{@"title":@"Allow Location Access",
    @"content":@"In order to show you nearby stores and discounts,as well as getting your location during emergency event,we need pertting access your device location and synchronize with your server securely."}];
    
    //contact
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    [[KAppConfig sharedConfig] setContactAuthorized:status == CNAuthorizationStatusAuthorized];
    
    self.tableView.loadmoreEnable = NO;
    self.tableView.refreshEnable = NO;
    [self.tableView registerClass:[KPermissionCell class] forCellReuseIdentifier:[KPermissionCell className]];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(locationAuthorizedChanged) name:KLocationAuthorizedStatusChangedNotification object:nil];
}

- (void)getData {
    [self showLoading];
    WEAKSELF
    HJVisitFriendInfoRequest *info = [[HJVisitFriendInfoRequest alloc] initWithKey:[KPartyView unarchive].uid];
    [info startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        HJVisitFriendInfoModel *model  = [HJVisitFriendInfoModel modelWithJSON:request.responseData];
        weakSelf.visitFriendInfoModel = model;
        if (model.statusCode == 200) {
            [weakSelf.tableView reloadData];
        } else {
            [weakSelf showErrorText:model.msg errCode:model.statusCode];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf showErrorText:request.responseString];
    }];
}

-(void)locationAuthorizedChanged{
    
    //location
    CLAuthorizationStatus locationStatus = [CLLocationManager authorizationStatus];
    [[KAppConfig sharedConfig] setLocationAuthorized:(locationStatus == kCLAuthorizationStatusAuthorizedAlways) || (locationStatus == kCLAuthorizationStatusAuthorizedWhenInUse)];
    [self.tableView reloadData];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.items.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KPermissionCell* cell = [tableView dequeueReusableCellWithIdentifier:[KPermissionCell className]];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

-(void)configureCell:(KPermissionCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    @weakify(self);
    NSString* title = [self.items[indexPath.section] objectForKey:@"title"];
    cell.fd_enforceFrameLayout = NO;
    cell.infoDic = self.items[indexPath.section];
    if ([@"Allow Contact List Access" isEqualToString:title]) {
        [cell.switchIB setOn:[self.visitFriendInfoModel.partyView.allowContactListAccess isEqualToString:@"Y"] ? YES : NO];
    }else if ([@"Allow Location Access" isEqualToString:title]){
//        if ([CLLocationManager locationServicesEnabled]) {
//            [cell.switchIB setOn:[KPartyView unarchive].allowLocationAccess];
//        }else{
//            [cell.switchIB setOn:NO];
//        }
        [cell.switchIB setOn:[self.visitFriendInfoModel.partyView.allowLocationAccess isEqualToString:@"Y"] ? YES : NO];
    }
    cell.operateBlock = ^(BOOL allow) {
        [weak_self operateWithTitle:title allow:allow];
    };
}

-(void)operateWithTitle:(NSString*)title allow:(BOOL)allow{
    if ([title isEqualToString:@"Allow Contact List Access"]) {
        NSString *isOn = allow ? @"Y" : @"N";
        GPContactRequest *request = [[GPContactRequest alloc] initWithURL:KUpdateprofileURL];
        request.isPost = YES;
        request.params = @{@"allowContactListAccess":isOn};
        WEAKSELF
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            NSDictionary *response = request.responseJSONObject;
            if ([response[@"statusCode"] integerValue] != 200) {
                [weakSelf showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
                return;
            }
            [weakSelf showSuccess:@"success"];
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf showErrorText:@"failture"];
        }];
        
    } else if ([title isEqualToString:@"Allow Location Access"]){
//        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//        if ([[UIApplication sharedApplication] canOpenURL:url]) {
//            [[UIApplication sharedApplication] openURL:url];
//        }
        NSString *isOn = allow ? @"Y" : @"N";
        GPContactRequest *request = [[GPContactRequest alloc] initWithURL:KUpdateprofileURL];
        request.isPost = YES;
        request.params = @{@"allowLocationAccess":isOn};
        WEAKSELF
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            NSDictionary *response = request.responseJSONObject;
            if ([response[@"statusCode"] integerValue] != 200) {
                [weakSelf showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
                return;
            }
            [weakSelf showSuccess:@"success"];
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf showErrorText:@"failture"];
        }];
    }
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:[KPermissionCell className] configuration:^(id cell) {
        [self configureCell:cell atIndexPath:indexPath];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
